import tkinter as tk
from tkinter import filedialog, ttk
from download import get_info, check, download, schedule


class MainWindow():
    def __init__(self):

        self.__win = tk.Tk(className='Bilibili')
        # 设置窗口长宽是否可变，0为不可变
        # self.__win.resizable(1, 1)
        # 窗口大小
        self.__win.geometry('700x400')
        # 窗口图标
        self.__win.iconbitmap('./img/bilibili.ico')

        tk.Label(text='视频网址：').place(x=100, y=1)

        self.__url_info = tk.Entry(self.__win)
        self.__url_info.place(x=180, y=3, width=380)
        # delete方法第一个参数表示从前或后开始删除，第二个参数表示一次删除的字符数
        tk.Button(self.__win, text='清空',
                  command=self.__clear_video_info).place(x=570,
                                                         y=0,
                                                         width=60,
                                                         height=25)

        tk.Label(text='视频数量：').place(x=100, y=36)
        self.__n_lb = tk.Label()
        self.__n_lb.place(x=160, y=36)

        tk.Label(text='视频质量：').place(x=380, y=36)
        self.__combox = ttk.Combobox(self.__win)
        self.__combox.place(x=440, y=36)

        tk.Button(self.__win, text='确定',
                  command=self.__video_info).place(x=636,
                                                   y=0,
                                                   width=60,
                                                   height=25)

        tk.Label(text='保存地址：').place(x=100, y=81)
        self.__file_info = tk.Entry(self.__win)
        self.__file_info.place(x=180, y=83, width=380)
        tk.Button(self.__win, text='浏览',
                  command=self.__set_path).place(x=570,
                                                 y=78,
                                                 width=60,
                                                 height=25)
        tk.Button(self.__win, text='确定',
                  command=self.__download).place(x=636,
                                                 y=78,
                                                 width=60,
                                                 height=25)

        # 进度条
        tk.Label(self.__win, text='下载总进度：').place(x=100, y=123)
        self.__canvas = tk.Canvas(self.__win, bg='white')
        self.__canvas.place(x=176, y=120, width=490, height=30)

        self.__text = tk.Text(self.__win)
        self.__text.place(x=100, y=160, height=220)

        self.__win.mainloop()

    def __video_info(self):

        try:
            # 网址有误就会返回False
            num, self.__qualitys = get_info(self.__url_info.get())
        except TypeError:
            tk.Label(self.__win, text='!', fg='red').place(x=80, y=1)
            return
        # 修改label值
        self.__n_lb.configure(text=num)
        # 设置下拉菜单内容
        self.__combox['value'] = tuple(self.__qualitys)
        # 下拉菜单默认值
        self.__combox.current(0)

    def __clear_video_info(self):
        """清除视频地址及其相关信息"""
        self.__url_info.delete(0, 100)
        self.__n_lb.configure(text='')
        self.__combox['value'] = ('', )
        self.__combox.current(0)

    def __set_path(self):
        """浏览文件夹"""
        # 先清空输入框内容
        self.__file_info.delete(-1, 100)
        self.__file_info.insert(0, filedialog.askdirectory())

    def __download(self):

        # 如果是第二遍下载，先将进度条还原成白色
        # 进度条填充颜色
        fill_line = self.__canvas.create_rectangle(0, 0, 0, 30, fill='white')
        self.__canvas.coords(fill_line, (0, 0, 490, 30))
        self.__win.update()
        # 视频保存路径
        path = self.__file_info.get()
        # 视频网址
        url = self.__url_info.get()
        # 视频个数
        num = self.__n_lb.cget('text')
        # 检查保存路径是否存在
        if not check(path):
            tk.Label(self.__win, text='!', fg='red').place(x=80, y=81)
            return
        # 检查是否输入网址
        if not url:
            tk.Label(self.__win, text='!', fg='red').place(x=80, y=1)
            return
        # 要确保download函数以较短时间执行完，否则界面会一直卡在这
        download(url, path, num, self.__qualitys.index(self.__combox.get()))
        # 创建画布填充形状
        fill_line = self.__canvas.create_rectangle(0, 0, 0, 30, fill='red')
        # 完成下载的视频个数
        finish = 0
        while finish < num:
            while schedule:
                finish += 1
                self.__text.insert(tk.END, f'{finish}\t{schedule.pop(0)}\n')

            self.__canvas.coords(fill_line, (0, 0, (finish / num * 490), 30))
            # 根据标签删除内容
            self.__canvas.delete('txt')
            self.__canvas.create_text(245,
                                      15,
                                      text=f'{int(finish / num * 100)}%',
                                      font=('楷体', 20),
                                      tags='txt')
            self.__win.update()


if __name__ == '__main__':
    MainWindow()
